set fileencoding=utf-8 " Set utf-8 encoding on write
scriptencoding utf-8

""""""""""""""""""""""""""""""
" ~ VIMRC ~ for Vim >= 8 && Neovim
" Author: Chris Jones
" Source: http://github.com/ipatch/dotfiles/blob/master/editors/vim/vimrc
" Source: https://git.io/vpEKR
""

""""""""""""""""""""""""""""""
" Notes / gotchas - some good things to know before hacking `~/.vimrc`
" NOTE: this rc file is being linted with `vint`
" NOTE: https://github.com/Kuniwak/vint
" NOTE: To print the value of a setting, ie. return the set value
" `:set autoindent?`
" SEE: `~/.vim/after/ftplugin/vim.vim` for settings related to `.vim`
""

" set this first, the default `leader` key is `\`
let g:mapleader = "\<Space>" " bind 'leader' key to spacebar

" Don't allow vi compatibility mode; don't need it 🤽
" NOTE: as of nov 2020, `nocompatible` is default for Vim ≥ 8.2 and Neovim
" set nocompatible "Enable at own risk, can have undesired effects
" SEE: `:help nocompatible` for more info.
""

"""""""""""""""""""""""""""""
" NOTE: Settings - June 23 2018 moved to `~/.vim/plugin/settings.vim`
""

"""""""""""""""""""""""""""""
" Key mappings / bindings
" NOTE: mappings - June 23 2018 moved to `~/.vim/plugin/mappings.vim`
""

""""""""""""""""""""""""""""""
" check for current OS
" NOTE: `:echo os` to print the variable value in the current buffer
" NOTE: if (n)vim has access to both clipboards it will put copy / paste operations into both clipboards.
""
function! GetRunningOS()
  if has('win32')
    return 'win32'
  elseif has('win32unix')
    return 'win32unix'
  elseif has('macunix')
    if !empty($TMUX)
      " echom 'wtf'
      " let g:clipboard+=tmux
      set clipboard+=unnamed,unnamedplus
    else
      set clipboard+=unnamed,unnamedplus
      " pbcopy for macOS copy/paste
      " vmap <C-x> :!pbcopy<CR>
      " vmap <C-c> :w !pbcopy<CR><CR>
    endif
    set shell=bash
    set runtimepath+=/usr/local/opt/fzf
    return 'macos'
  elseif has ('unix')
    if system('uname')=~?'Linux'
      if !empty($TMUX)
        " TODO: figure out how to set clipboard properly through ssh
        " let g:clipboard+=tmux
        " set clipboard+=xsel
      else
        " set clipboard+=xsel
      endif 
      set shell=bash
      set runtimepath+=/home/linuxbrew/.linuxbrew/bin/fzf
      return 'linux'
    endif
  else
    " catch all 🎣 for everything else
    " No love 💔 for the other guys
  endif
endfunction
let g:os = GetRunningOS()

function! SetupCommandAlias(from, to)
  " NOTE: useful for aliasing `PackUpdate` to `packupdate` etc...
  exec 'cnoreabbrev <expr> '.a:from
        \ .' ((getcmdtype() is# ":" && getcmdline() is# "'.a:from.'")'
        \ .'? ("'.a:to.'") : ("'.a:from.'"))'
endfunction

""""""""""""""""""""""""""""""
" fonts
""
highlight Comment gui=italic
highlight Comment cterm=italic
let &t_8f="\<Esc>[38;2;%lu;%lu;%lum"
let &t_8b="\<Esc>[48;2;%lu;%lu;%lum"
set termguicolors " use guifg/guibg instead of ctermfg/ctermbg in terminal

"""""""""""""""""""""""""""""
" conceal levels
" toggle between different conceal levels
" NOTE: `indentLine` will control conceal levels if installed
""
function! ToggleConcealLevel()
  if &conceallevel == 0
    setlocal conceallevel=2
  elseif &conceallevel == 1
    setlocal conceallevel=0
  elseif &conceallevel == 2
    setlocal conceallevel=0
  endif
endfunction

nnoremap <silent> ` :call ToggleConcealLevel()<CR>

" set default conceal level
set conceallevel=0 " DO NOT conceal any text
let g:indentLine_fileTypeExclude = ['json']

"""""""""""""""""""""""""""""
" netrw - file explorer
" CREDIT: https://shapeshed.com/vim-netrw/   
""

let g:netrw_liststyle = 3 " tree style
let g:netrw_banner = 0 " Do not display the banner when using Netrw
let g:netrw_browse_split = 1 " TODO: figure out what this variable does ???
let g:netrw_winsize = 25 " set the default width for netrw
" TODO: document what the below variable does to netrw
let g:netrw_altv = 1
" Set atom style macOS key binding to open the project drawer
" CREDIT: https://stackoverflow.com/a/23069285/708807
" NOTE: toggling netrw sucks!
" TODO: get a sane toggle expierence going ...eventually!
nnoremap <M-\> :Lexplore<cr>
inoremap <M-\> :Lexplore<cr>
" OPTIONAL: keep netrw browsing dir the same as current dir
" `let g:netrw-keepdir = 0`

" https://vi.stackexchange.com/a/13012
" Per default, netrw leaves unmodified buffers open. This autocommand
" deletes netrw's buffer once it's hidden (using `:q`, for example)
augroup netrw_delete_hidden_augroup
  autocmd!
  autocmd FileType netrw setl bufhidden=delete
augroup END

"----------------------------
" Autocommands relocated to `~/.vim/plugin/autocmds.vim`
""

"----------------------------
" wildmenu -  completion
"-
if has('wildmenu')
  set wildmenu " display menu when using `tab` completeion
  set wildmode=full " Specifies how the `tab` completion works in wildmenu
  set wildignore=*.o,*.obj,*~ "stuff to ignore when tab completing
  set wildignore+=*/.git/* " ignore the below directories with wild menu
  set wildignore+=*logs*
  set wildignore+=*node_modules/**
  set wildignore+=package-lock.json
  set wildignore+=yarn.lock
  set wildignore+=*DS_Store*
  set wildignore+=*.gem
  set wildignore+=log/**
  set wildignore+=_build/**
  set wildignore+=*.bmp,*.gif,*.ico,*.jpg,*.png,*.pdf,*.psd,session.vim
  set wildignore+=tags
endif

" NOTE: clone minpac first before installing plugins.
set packpath^=~/.vim
" Try to load minpac.
silent! packadd minpac

function! BuildStaticVimMarkdownComposer()
  " if a:info.status != 'unchanged' || a:info.force
    if has('nvim')
      !(cd '/opt/code/dotfiles/editors/vim/vim/pack/minpac/start/vim-markdown-composer'; cargo +nightly build --release)
      " !cargo build --release
    elseif v:version > 8 || v:version == 8 " Check for Vim8 ...sort of
      !(cd '/opt/code/dotfiles/editors/vim/vim/pack/minpac/start_vim8/vim-markdown-composer';cargo build --release --no-default-features --features json-rpc)
      " Explicity set path for Vim8 build of vim-markdown-composer
      set runtimepath+=/opt/code/dotfiles/editors/vim/vim/pack/minpac/start_vim8/vim-markdown-composer
      set runtimepath-=/opt/code/dotfiles/editors/vim/vim/pack/minpac/start/vim-markdown-composer
    endif
endfunction

" plugin specfic settings
" let g:markdown_composer_autostart = 1
" let g:ale_completion_enabled = 1

function! FixupBase16()
  !(sed -i '/Base16hi/\! s/a:\(attr\|guisp\)/l:\1/g' /opt/code/dotfiles/editors/vim/vim/pack/minpac/start/base16-vim/colors/*.vim)
endfunction

" below `if` block/statement stopped working on september 26, 2020
" if !exists('*minpac#init')
" SEE: advanced sample on github readme of minpac
if !exists('g:loaded_minpac')
  " minpac is NOT available
  echo 'Yo!, you need minpac dawg!'
  " Settings for plugin-less, ie. no minpac 😥 environment.
  if empty(glob('~/.vim/pack/minpac/opt/minpac/plugin/minpac.vim'))
    silent !curl -fLo ~/.vim/pack/minpac/opt/minpac/plugin/minpac.vim
          \--create-dirs
          \https://raw.githubusercontent.com/k-takata/minpac/master/plugin/minpac.vim 
    autocmd VimEnter * packadd minpac
    call minpac#init()
    call minpac#add('k-takata/minpac', {'type': 'opt'})
  endif
else
  " minpac found
  call minpac#init()
  call minpac#add('k-takata/minpac', {'type': 'opt'})

  "-----------------------------
  " Load additional plugins
  "-
  call minpac#add('machakann/vim-highlightedyank') " name says it all
  call minpac#add('chriskempson/base16-vim') " UX goodness
  call minpac#add('Yggdroot/indentLine') " vert indent lines
  call minpac#add('tpope/vim-commentary') " quickly comment lines
  call minpac#add('sheerun/vim-polyglot') " lazy load syntax hl
  call minpac#add('christoomey/vim-tmux-navigator') " vim&tmux navi
  call minpac#add('tpope/vim-fugitive') " display git branch
  call minpac#add('itchyny/lightline.vim') " lightweight status line.
  call minpac#add('rust-lang/rust.vim')
  " call minpac#add('euclio/vim-markdown-composer')
  " call minpac#add('euclio/vim-markdown-composer', {'type': 'opt'})
  call minpac#add('majutsushi/tagbar')
  "
  " call minpac#add('joshdick/onedark.vim') " exp with new colorscheme
  " call minpac#add('w0rp/ale') " Asynchronous Linting Engine
  " call minpac#add('tpope/vim-obsession') " auto session mgmt
  " call minpac#add('MaxMEllon/vim-jsx-pretty') " syntax highlight

  "-----------------------------
  " minpac - conditional plugins
  "---------------------------------------------------------------
  " neovim only plugins!!!
  "---------------------------------------------------------------
  ""
  if has('nvim')
     call minpac#add('Shougo/denite.nvim')
    " call minpac#add('Shougo/denite.nvim', {'rev': '29bfd4c53271c7a150def2388e059746ae4c1713'})
     call minpac#add('neoclide/coc.nvim', {'branch': 'release'})
  elseif v:version > 8 || v:version == 8 " Check for Vim8 ...sort of
    call minpac#add('autozimu/LanguageClient-neovim', {'type': 'opt',
          \'branch': 'next', 'do': {-> system('bash install.sh')}})
  endif
  
  "----------------------------
  " minpac - Custom commands
  "-
  command! PackUpdate packadd minpac | source $MYVIMRC | call minpac#update('', {'do': 'call minpac#status()'})
  command! PackClean  packadd minpac | source $MYVIMRC | call minpac#clean()
  command! PackList echo join(minpac#getpackages("minpac", "start"), "\n")
  command! PackStatus packadd minpac | source $MYVIMRC | call minpac#status()

  call SetupCommandAlias("packupdate", "PackUpdate")
  call SetupCommandAlias("packclean", "PackClean")
  call SetupCommandAlias("packstatus", "PackStatus")
endif

"----------------------------
" DANGER ZONE > experimental settings
"-


" exp with floating window for fuzzy searching for files using fzf

" " floating fzf
" if has('nvim')
"   let $FZF_DEFAULT_OPTS .= '--layout=reverse'

"   function! FloatingFZF()
"     let height = &lines
"     let width = float2nr(&columns - (&columns * 2 / 10))
"     let col = float2nr((&columns - width) / 2)
"     let col_offset = &columns / 10
"     let opts = {
"     \ 'relative': 'editor',
"     \ 'row': 1,
"     \ 'col': col + col_offset,
"     \ 'width': width * 2/ 1,
"     \ 'height': height / 2,
"     \ 'style': 'minimal'
"     \ }
"     let buf = nvim_create_buf(v:false, v:true)
"     let win = nvim_open_win(buf, v:true,opts)
"     call setwinvar(win, '&winhl', 'NormalFloat:TabLine')
"   endfunction

"   let g:fzf_layout = { 'window': 'call FloatingFZF()' }
" endif


"----------------------------
" END < DANGER ZONE
"-

" Setting for rust.vim
" TODO: move to language specific setting file, ie. `rust.vim`
let g:autofmt_autosave = 1

"----------------------------
" For Neovim's eyes only 
"-
if has('nvim')
  let g:loaded_sensible=0
  " Keymappings for Neovim
  " Neovim defaults to `<C-\><C-n>` to exit a virtual terminal
  tnoremap <Esc> <C-\><C-n>
  tnoremap <A-[> <Esc>

  if has('nvim-0.1.5')
    set termguicolors " use guifg/guibg instead of ctermfg/ctermbg in terminal
    hi Cursor guifg=green guibg=green
    hi Cursor2 guifg=red guibg=red
    set guicursor=n-v-c:block-Cursor/lCursor,i-ci-ve:ver25-Cursor2/lCursor2,r-cr:hor20,o:hor50
  elseif
    let $NVIM_TUI_ENABLE_TRUE_COLOR = 1 " Legacy way to enable 24bit color.
  endif
endif " END Neovim only settings

""""""""""""""""""""""""""""""
" colorscheme
""
" NOTE: make scope explicit, ie. `let g:[mr-fancy-setting]` NOT `let
" [mr-fancy-setting`
"let g:base16colorspace = 256 " Access colors present in 256 colorspace

  "onedark.vim override: Set a custom background color in the terminal
  " NOTE: set custom gui settings for `ondark.vim` BEFORE init colorscheme
  if (has("autocmd") && !has("gui_running"))
    augroup colors
      autocmd!
      let s:background = { "gui": "#101010", "cterm": "235", "cterm16": "0" }
      autocmd ColorScheme * call onedark#set_highlight("Normal", { "bg": s:background }) "No `fg` setting
    augroup END
  endif

  if (has("autocmd"))
    augroup colorextend
      autocmd!
      " Make `Function`s bold in GUI mode
      autocmd ColorScheme * call onedark#extend_highlight("Function", { "gui": "bold" })
      " Override the `Statement` foreground color in 256-color mode
      autocmd ColorScheme * call onedark#extend_highlight("Statement", { "fg": { "cterm": 128 } })
      " Override the `Identifier` background color in GUI mode
      " autocmd ColorScheme * call onedark#extend_highlight("Identifier", { "bg": { "gui": "#333333" } })
      autocmd ColorScheme * call onedark#extend_highlight("FoldColumn", { "fg": { "gui": "#4b5263" } })
    augroup END
  endif
  " TODO: add check if colorscheme is not present, and continue loading file
  " colorscheme base16-default-dark
  colorscheme onedark

""""""""""""""""
" load before plugins - polyglot
""
" let g:polyglot_disabled = ['json']
